package com.nuanshui.heatedloan.baseservice.service;

import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.fastjson.JSON;
import com.nuanshui.framework.behavior.BehaviorContext;
import com.nuanshui.framework.exception.BizException;
import com.nuanshui.framework.exception.GlobalErrorCode;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.baseservice.facade.BaseService;
import com.nuanshui.heatedloan.baseservice.model.UserAgent;
import com.nuanshui.heatedloan.constant.DubboTransferConstant;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.dubbo.DubboResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * Created by zss on 2017/4/14.
 * 
 */
public class DubboServiceImpl implements BaseService {

	protected Logger log = LoggerFactory.getLogger(this.getClass());
	protected Logger logicLog = LoggerFactory.getLogger("LOGIC");
	protected Logger bizErrorLog = LoggerFactory.getLogger("biz_log");

	public DubboServiceImpl() {

	}

	public String getHeaderString(String key) {

		String val=(String)BehaviorContext.getContext().get(key);
		return val;

	}

	public void error(String msg) {
		LogUtil.info(this.bizErrorLog, msg);
		throw new BizException(GlobalErrorCode.UNKNOWN, msg);
	}
	
	public HttpServletRequest getRequest() {
		return null;
	}

	// 获取当前的用户信息
	public String getCurrentUserInfo() {
		return getHeaderString(DubboTransferConstant.DUBBO_SERVER_CURRENTUSER);
	}

	// 获取当前用户的channel
	public String getCurrentChannel() {

		UserAgent userAgent = new UserAgent();
		if (userAgent != null)
			return getUserAgent().getChannel();

		return null;
	}

	// 获取当前用户的userid
	public String getCurrentUserId() {
		return getHeaderString(DubboTransferConstant.DUBBO_SERVER_USERID);
	}
	
	// 判断是不是来自于微信
	public boolean isFromWechat() {
		String channel = getCurrentChannel();
		if (StringUtils.isNotEmpty(channel)) {
			if ("weixin".equals(channel))
				return true;
		}
		return false;
	}

	// 获取当前的openId
	public String getCurrentOpenId() {
		return getHeaderString(DubboTransferConstant.DUBBO_SERVER_OPENID);
	}

	// 获取DubboResponse
	public DubboResponse success(Object object) {
		DubboResponse dubboResponse = new DubboResponse();
		dubboResponse.setData(object);
		return dubboResponse;
	}

	@Override
	public UserAgent getUserAgent() {
		String userAgent=getHeaderString(GlobalParam.USER_AGENT);
		if(SysStringUtils.isNotEmpty(userAgent))
		   return JSON.parseObject(userAgent,UserAgent.class);
		
		return null;
	}

	@Override
	public String getWechatOpenId() {
		return getCurrentOpenId();
	}
}
